package com.zry.traced.ui.activity

import android.content.Context
import android.text.Editable
import android.text.InputFilter
import android.text.TextWatcher
import android.view.inputmethod.InputMethodManager
import com.zry.traced.R
import com.zry.traced.adapter.TraceCodeListAdapter
import com.zry.traced.animation.RecyclerViewUtilKt
import com.zry.traced.databinding.ActivityBatchStorageBinding
import com.zry.traced.presenter.BatchStoragePresenter
import com.zry.traced.utils.InputCodeFilter
import android.util.Log

import com.zry.traced.been.*
import com.zry.traced.greendao.entity.OutTreasuryCode
import com.zry.traced.greendao.entity.PackingOperationInfo

import com.zry.traced.presenter.HttpServer
import com.zry.traced.retrofit.ShowUserView
import com.zry.traced.ui.base.BaseActivity
import com.zry.traced.utils.KeyboardUtils
import kotlinx.android.synthetic.main.activity_batch_storage.*
import kotlinx.android.synthetic.main.common_title.*


class BatchStorageActivity : BaseActivity(), ShowUserView {


    private var batchStorageBinding: ActivityBatchStorageBinding? = null
    private var batchStoragePresenter: BatchStoragePresenter? = null
    private var traceCodeListAdapter: TraceCodeListAdapter? = null
    private var mInputMethodManager: InputMethodManager? = null

    var longAndShortCodeList: ArrayList<LongAndShortCode>? = null
    var title = ""

    var storeOrderBean: StoreOrderBean? = null
    var packingOperationInfo: PackingOperationInfo? = null
    var outStock: OutStock? = null
    var outTreasuryCode: OutTreasuryCode? = null


    override fun getLayoutId(): Int {
        return R.layout.activity_batch_storage
    }

    override fun initData() {

        title = intent.getStringExtra("title")
        submitConfirmPutStorageBtn.text = intent.getStringExtra("title")

        when (title) {
            "批量入库", "号段入库" -> {
                storeOrderBean = intent.getSerializableExtra("storeOrderBean") as StoreOrderBean
            }
            "批量出库", "号段出库" -> {
                outStock = intent.getSerializableExtra("outStock") as OutStock
                outTreasuryCode = intent.getSerializableExtra("outTreasuryCode") as OutTreasuryCode
            }
            "批量装箱", "号段装箱" -> {
                packingOperationInfo = intent.getSerializableExtra("packingOperationInfo") as PackingOperationInfo
            }
        }


        titleCenterText.text = title
        commonLeftLinearLayout.setOnClickListener { finish() }
        batchStorageBinding = viewDataBinding as ActivityBatchStorageBinding
        batchStoragePresenter = BatchStoragePresenter(this)
        batchStorageBinding?.handlerClick = batchStoragePresenter
        //初始化输入法
        mInputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager


        longAndShortCodeList = arrayListOf()
        initRecycler()
        initView()
    }

    private fun initRecycler() {
        recyclerViewUtilKt = RecyclerViewUtilKt(this, batchStorageRecycler)
        recyclerViewUtilKt?.initRecyclerView()
        traceCodeListAdapter = TraceCodeListAdapter(R.layout.trace_code_item, longAndShortCodeList!!)
        recyclerViewUtilKt?.setAdapter(traceCodeListAdapter!!)
        traceCodeListAdapter?.setOnItemChildClickListener { adapter, view, position ->
            when (view.id) {
                R.id.traceCodeDeleteImg -> {
                    longAndShortCodeList!!.removeAt(position)
                    traceCodeListAdapter?.notifyDataSetChanged()
                }
            }
        }
    }

    private fun initView() {
        codeScanEditText.filters = arrayOf<InputFilter>(InputCodeFilter())
        codeScanEditText.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) = Unit
            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) = Unit
            override fun afterTextChanged(p0: Editable?) {
                val codeString = codeScanEditText.text.toString().trim()
                Log.e("codeString", codeString)
                if (!codeString.isEmpty()) {
                    setRequestFocusFalse()
                    setLongCode(codeString)
                } else {
                    getEditFocusTrue()
                }
            }
        })
    }

    fun setLongCode(codeString: String) {
        when (title) {
            "批量入库", "号段入库" -> {
                when (storeOrderBean?.StoreType) {
                    "1" -> {
                        //追溯码
                        HttpServer(this).getLongTraceCode(codeString, storeOrderBean!!.ProductID, "2", "", this)
                    }
                    "2", "3" -> {
                        //流通码
                        HttpServer(this).getLongCirculationCode(codeString, storeOrderBean!!.ProductID, "2", storeOrderBean!!.StoreType, "", this)
                    }
                }
            }

            "批量装箱", "号段装箱" -> {
                when (packingOperationInfo?.packLevelID) {
                    "2" -> {
                        //追溯码
                        HttpServer(this).getLongTraceCode(codeString, packingOperationInfo!!.productID, "1", "", this)
                    }
                    "3" -> {
                        //流通码
                        HttpServer(this).getLongCirculationCode(codeString, packingOperationInfo!!.productID, "1", packingOperationInfo!!.packLevelID, "", this)
                    }
                }
            }
            "批量出库", "号段出库" -> {
                when (outTreasuryCode?.outLevelID) {
                    "1" -> {
                        //追溯码
                        HttpServer(this).getLongTraceCode(codeString, outTreasuryCode!!.productID, "3", "", this)
                    }
                    "2", "3" -> {
                        //流通码
                        HttpServer(this).getLongCirculationCode(codeString, outTreasuryCode!!.productID, "3", outTreasuryCode!!.outLevelID, "", this)
                    }
                }
            }
        }
    }

    override fun toMainActivity(what: Int, data: Any) {

        when (what) {
            5 -> {
                val resultData = data as ResultCode
                if (resultData.state == "1") {
                    val longAndShortCode = LongAndShortCode(resultData.CodeID, resultData.shortCode)
                    notifyAdapter(longAndShortCode)
                } else {
                    toast(resultData.Message)
                    codeScanEditText.setText("")
                    getEditFocusTrue()
                    KeyboardUtils().hideKeyboard(this)
                }
            }

            6 -> {
                val resultData = data as ResultFlowCode
                if (resultData.state=="1"){
                    val longAndShortCode = LongAndShortCode(resultData.Code, resultData.shortCode)
                    notifyAdapter(longAndShortCode)
                }else{
                    toast(resultData.Message)
                    codeScanEditText.setText("")
                    getEditFocusTrue()
                    KeyboardUtils().hideKeyboard(this)
                }
            }
        }
    }


    private fun notifyAdapter(longAndShortCode: LongAndShortCode) {
        when {
            longAndShortCodeList!!.contains(longAndShortCode) -> toast("此追溯码已存在列表中")
            else -> {
                longAndShortCodeList!!.add(longAndShortCode)
                traceCodeListAdapter?.notifyDataSetChanged()
            }
        }
        codeScanEditText.setText("")
        getEditFocusTrue()
        KeyboardUtils().hideKeyboard(this)
    }


    fun getEditFocusTrue() {
        //获取焦点
        codeScanEditText.isFocusable = true
        codeScanEditText.isFocusableInTouchMode = true
        //显示光标
        codeScanEditText.requestFocus()
        codeScanEditText.isCursorVisible = true
    }

    fun setRequestFocusFalse() {
        //取消焦点
        codeScanEditText.isFocusable = false
        codeScanEditText.isFocusableInTouchMode = false
        //隐藏光标
        codeScanEditText.isCursorVisible = false
    }
}
